<?php
namespace admin\service;

/**--tmpl-use--**/
use herosphp\core\Loader;
use herosphp\bean\Beans;
use herosphp\session\Session;
use herosphp\web\WebUtils;

/**--tmpl-import--**/

class RbacService extends CommonService{

	const MANAGER_SESSION_NAME = 'mpe_manager_session_name';

	private $adminManagerDao = null;

	private $adminRoleDao = null;
	private $adminNodeDao = null;
	private $adminManagerRoleDao = null;
	private $adminRoleNodeDao = null;

	public function __construct($model) {
			parent::__construct($model);

		$this->adminManagerDao = Loader::model('adminManager');
		$this->adminRoleDao = Loader::model('adminRole');
		$this->adminNodeDao = Loader::model('adminNode');
		$this->adminManagerRoleDao = Loader::model('adminManagerRole');
		$this->adminRoleNodeDao = Loader::model('adminRoleNode');
	}


	//获取当前管理员的所有可用模块配置
	public function getCurrentManagerAvailableModuleConfig(){
		$module_config = L('MODULE_CONFIG');
		$n = $this->getCurrentManagerAvailableNodes();
		$r = array();
		/*
		foreach($n as $v){
			$nodeDetail = explode('/',$v['node_key']);
			foreach($module_config as $kk => $vv){
				if(in_array($nodeDetail[1],array_keys($vv))){
					$r[$kk] = $vv;
				}
			}
		}*/
		foreach($module_config as $kk => $vv){

			foreach($n as $v){

			    $nodeDetail = explode('/',$v['node_key']);
				if(in_array($nodeDetail[1],array_keys($vv))){
					$r[$kk] = $vv;
				}
			}
		}

		return $r;
	}
	//获取当前管理id
	public function  getAdminId(){
		Session::start();
		if(isset($_SESSION[self::MANAGER_SESSION_NAME])){
			return $_SESSION[self::MANAGER_SESSION_NAME]['id'];
		}
		else{
			return 0;
		}
	}

	//获取当前管理员名字
    public function  getAdminName(){
        Session::start();
        if(isset($_SESSION[self::MANAGER_SESSION_NAME])){
            return $_SESSION[self::MANAGER_SESSION_NAME]['username'];
        }
        else{
            return "";
        }
    }

	//获取当前管理员所有可用的权限信息
	public function getCurrentManagerAvailableNodes()
	{
		$adminId = $this->getAdminId();
		return $this->getUserNodes($adminId);

	}

	//获取当前管理员拥有的权限
	public function getCurrentManagerPrivileges(){
		$nodes = $this->getCurrentManagerAvailableNodes();
		$priv = array();
		foreach($nodes as $v){
			$tmp = $v['node_key'];	
			$arr = explode('/',$tmp);

			if(!in_array($arr[1],$priv)){
				$priv[] = $arr[1];	
			}
			if(!in_array($arr[0]. '/' . $arr[1],$priv)){
				
				$priv[] = $arr[0] . '/' . $arr[1];
			}
			$priv[] = $arr[0] . '/' .  $arr[1] . '/' . $arr[2];
		}

		return $priv;
	}

	/*
	 * 判断是否有权限
	 * 
	 */
	public function hasPermission($operation)
	{
		$operation = strtolower($operation);
		$operation = str_replace('/do_','/',$operation);
		$operation = str_replace('/deletes','/delete',$operation);
		$privs = $this->getCurrentManagerPrivileges();
		$manager = $this->getLoginManager();
		if($manager['role_id'] == 0)
		{
			//如果是超级管理员
			return true;	
		}

		if(in_array($operation,$privs))
		{
			return true;	
		}
		$allPriv = $this->getNodeArray();
		foreach($allPriv as $v)
		{
			if($v['node_key'] == $operation)
			{
				return false;	
			}	
		}
		return true;
		
	}

	//获取用户拥有的权根数组
	public function getUserNodes($userid){


		static $lifeCache = array();
		if($lifeCache[$userid]){
			return $lifeCache[$userid];
		}
		$userinfo = $this->getItem($userid);

		$role_id = $userinfo['role_id'];
		if($role_id == 0){
			//超级管理员
			return $this->adminNodeDao->getNodeArray();

		}

		$rs = $this->adminRoleNodeDao->getItems(array('role_id' => $role_id),array('node_id'));
		$node_ids = array();
		foreach($rs as $v){
			$node_ids[] = $v['node_id'];
		}
		$nodes = $this->adminNodeDao->getItems(array('id' => array('$in' => $node_ids)));
		$lifeCache[$userid] = $nodes;
		return $nodes;
	}

	public function getItem($conditions, $fields, $order)
	{
		if(is_array($conditions)){
			$conditions['del_status'] = 0;
		}
		else{
			$id = $conditions;
			$conditions = array('del_status' => 0,'id' => $id);
		}
		$item = $this->adminManagerDao->getItem($conditions, $fields, $order);
		if(!$item) return NULL;
		/**--tmpl-todo--**/

		/**-- foreignitem --**/
		$admin_manager_role = $this->adminManagerRoleDao->getItem($item['role_id']);

		$item['role_name'] = $admin_manager_role['name'];
		//----------------------
		/**--tmpl-daoassoctodo--**/
		return $item;
	}

	/*
 * @override
 */
	public function getItems($conditions, $fields, $order, $limit, $group, $having)
	{
		$conditions['del_status'] = 0;
		$items = parent::getItems($conditions, $fields, $order, $limit, $group, $having);
		if(!$items) return NULL;

		/**--tmpl-todo--**/

		/**-- foreigncondi --**/
		$admin_manager_rolecondi = array();
		$admin_manager_managercondi = array();
		foreach($items as $k => $v)
		{
			if($v['role_id'])
			{
				$admin_manager_rolecondi[] = $v['role_id'];
			}
			if($v['manager_id'])
			{
				$admin_manager_managercondi[] = $v['manager_id'];
			}
		}

		$admin_roles = $this->adminRoleDao->getItems(array('id' => array( '$in' => $admin_manager_rolecondi)));
		$admin_manager = $this->modelDao->getItems(array('id' => array('$in' => $admin_manager_managercondi)));

		/**-- foreignforeach  --**/
		foreach ($items as $k => $v)
		{
			/**--tmpl-foreignfill--**/

			/**-- foreigneach --**/
			foreach($admin_roles as $kk => $vv)
			{
				if($vv['id'] == $v['role_id'])
				{
					/**--tmpl-fieldfill--**/

					$items[$k]['role_name'] = $vv['name'];

				}
			}
			foreach($admin_manager as $kk => $vv)
			{
				if($vv['id'] == $v['manager_id'])
				{
					$items[$k]['manager_name'] = $vv['name'];
				}
			}

		}
		return $items;
	}

	// see RbacService::getNodeArray
	public function getNodeArray(){
	
		return $this->adminNodeDao->getNodeArray();

	}


	/**--tmpl-method--**/

    /**
     * 管理员登陆
     * @param $username
     * @param $password
     * @return mixed
     */
    public function login($username, $password)
    {
		$condition = array('username' => $username, 'password' => passwd($password));
        $user = $this->adminManagerDao->getItem($condition);
        if ( $user != false ) {
            //存储session
            Session::start();
			session_start();
			$session_id = session_id();
            $_SESSION[self::MANAGER_SESSION_NAME] = $user;
			$_SESSION[self::MANAGER_SESSION_NAME]['priv'] = $this->getCurrentManagerPrivileges();

            //更新最后登陆ip和登录时间
            $lastLoginTime = date('Y-m-d H:i:s');
            $lastLoginIp = WebUtils::getClientIP();
			$this->adminManagerDao->update(array('updatetime'=>$_SESSION[self::MANAGER_SESSION_NAME]['updatetime'],'last_login_time' => $lastLoginTime, 'last_login_ip' => ip2long($lastLoginIp),'session_id' => $session_id), $user['id']);

            //记录登陆日志
            $loginLogService = Beans::get('admin.adminManagerLoginLog.service');
            $data = array(
                'username' => $username,
                'name' => $user['name'],
                'ip' => $lastLoginIp,
                'addtime' => $lastLoginTime
            );
            $loginLogService->add($data);
        }
        return $user;
    }

	/*
	* 修改Session 的个人信息
	* @param $myInfo : 修改过的个人信息
	* @return 
	 */

	public function updateMyInfo($myInfo){
		
		foreach($myInfo as $k =>  $v){
			$_SESSION[self::MANAGER_SESSION_NAME][$k] = $v;	
		}
	}

    /**
     * 获取登陆的管理员
     * @return mixed
     */
    public function getLoginManager()
    {
        Session::start();
        if ( isset($_SESSION[self::MANAGER_SESSION_NAME]) ) {
            return $_SESSION[self::MANAGER_SESSION_NAME];
        } else {
            return false;
        }
    }

    /**
     * 判断当前用户是否登陆
     * @return bool
     */
	public function isLogin()
    {
        Session::start();
		session_start();
		$settingService = Beans::get('admin.adminSetting.service');
		$onePointLogin = $settingService->getSetting('onePointLogin');
		if(!isset($_SESSION[self::MANAGER_SESSION_NAME]))
		{
			return false;
		}
		//单点登录开启
		//if($onePointLogin == 'on'){
			$session_id = session_id();
			$info = $this->adminManagerDao->getItem(array('id' =>$_SESSION[self::MANAGER_SESSION_NAME]['id']));
			//当前session_id 与最新登录用户session_id 不一致 ，强制下线
			if($info['session_id'] != $session_id){
				$_SESSION = null;
				session_destroy();	
				return false;
			}
		//}
		$sessionExpr = $settingService->getSetting('sessionExpr');
		if(!$sessionExpr){
			$sessionExpr = 30;
		}
		$prev_op_time = $_SESSION[self::MANAGER_SESSION_NAME]['prev_op_time'] ? $_SESSION[self::MANAGER_SESSION_NAME]['prev_op_time'] : time(0);
		if(!$prev_op_time){ $prev_op_time = time(0); }

		//判断登录是否超时
		if(((time(0) - $prev_op_time) / 60) > $sessionExpr){
			$_SESSION = null;
			session_destroy();	
			return false;
		}
		else{
			$_SESSION[self::MANAGER_SESSION_NAME]['prev_op_time'] = time(0);
		}
        return isset($_SESSION[self::MANAGER_SESSION_NAME]);
    }

    /**
     * 登出
     * @return mixed
     */
    public function logout()
    {
        Session::start();
        $_SESSION = null;
        session_destroy();
    }

}

